﻿using UnityEngine;

/// <summary>
/// 基于Mono的单例类
/// </summary>
public abstract class USaSingletonBase<T> : USaBehaviour where T : USaSingletonBase<T>
{
    /// <summary>
    /// 静态单例
    /// </summary>
    public static T instance => s_Instance ?? CreateInstance();

    private static T s_Instance;
    private static T CreateInstance()
    {
        s_Instance = FindObjectOfType<T>();
        if (s_Instance == null)
        {
            var go = new GameObject(typeof(T).Name);
            s_Instance = go.AddComponent<T>();
        }
        DontDestroyOnLoad(s_Instance);
        s_Instance.OnInit();
        return s_Instance;
    }

    private void Awake()
    {
        if (s_Instance == null)
        {
            CreateInstance();
        }
    }

    protected virtual void OnInit() { }
}